package com.weme.common.dialog

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.QuickViewHolder
import com.jeremyliao.liveeventbus.LiveEventBus
import com.weme.common.R
import com.weme.common.adapter.GiftChildAdapter
import com.weme.common.base.BaseDialog
import com.weme.common.databinding.DialogGiftBinding
import com.weme.common.manager.GetGiftListReplyManager
import com.weme.common.util.LiveConfig.NET_WORK_GIFT
import com.weme.common.util.LiveConfig.NET_WORK_MINE
import com.weme.common.util.gone
import com.weme.common.util.showToast
import com.weme.common.util.visible
import com.weme.common.viewmodel.GiftViewMode
import dev.kratos.api.user_server.v1.GetAccountInfoReply
import dev.kratos.api.user_server.v1.GetGiftListReply
import dev.kratos.api.user_server.v1.GetGiftListRequest
import dev.kratos.api.user_server.v1.GiftInfo


interface GiftDialogCallback {
    fun sendGiftInfo(giftInfo: GiftInfo)
}

class GiftDialog(var userName: String, private val callback: GiftDialogCallback) : BaseDialog() {
    val dataList = mutableListOf<List<GiftInfo>>()

    private lateinit var binding: DialogGiftBinding
    private var viewModel: GiftViewMode? = null
    override fun onStart() {
        super.onStart()
        dialog?.window?.apply {
            attributes.windowAnimations = R.style.DialogAnimation
            this.setWindowAnimations(R.style.SlideUpAnimation)
            setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            val params = attributes
            params.gravity = Gravity.BOTTOM // 将对话框的重心设置为底部
            params.width = ViewGroup.LayoutParams.MATCH_PARENT // 设置对话框宽度为全屏
            attributes = params
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        binding = DialogGiftBinding.inflate(inflater, container, false)

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // binding = DialogGiftBinding.inflate(LayoutInflater.from(context), null, false) //   giftAdapter = GiftAdapter(requireContext(),listOf("", "", "", "", ""))
        //  binding.banner.setAdapter(giftAdapter,false).setIndicator(CircleIndicator(requireContext())).addBannerLifecycleObserver(this)
        viewModel = ViewModelProvider(this)[GiftViewMode::class.java]
        viewModel?.getAccountInfo()
        if (!TextUtils.isEmpty(userName)) {
            binding.tvGiftTop.visible()
            binding.tvGiftTop.text = String.format(getString(com.example.resources.R.string.gift_top), userName)
        } //        adapter = BannerAdapter(requireContext(), dataList) {
        //            callback.sendGiftInfo(it)
        //        }
        binding.llSend.setOnClickListener {
            selectBean?.let { it1 ->
                callback.sendGiftInfo(it1)
            }


        }
        binding.vClickCoins.setOnClickListener {
            showToast("跳转金币商城")
        }
        binding.rcvList.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false).apply {
            initialPrefetchItemCount = 0
            isItemPrefetchEnabled = false
        }
        binding.rcvList.adapter = giftAdapter


        giftAdapter.submitList(dataList)

        val pagerSnapHelper = PagerSnapHelper()
        pagerSnapHelper.attachToRecyclerView(binding.rcvList)
        binding.rcvList.scrollToPosition(0)

        binding.rcvList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val layoutManager = recyclerView.layoutManager as LinearLayoutManager?
                val firstVisibleItemPosition = layoutManager?.findFirstVisibleItemPosition() ?: 0
                binding.vCircle.setCurrentPage(firstVisibleItemPosition)

                // 获取当前可见的第一个子 RecyclerView
                val currentView = layoutManager?.findViewByPosition(firstVisibleItemPosition)
                val childRecyclerView = currentView?.findViewById<RecyclerView>(R.id.rcvList)
                childRecyclerView?.let {
                    // 滚动到第一个 item
                    it.scrollToPosition(0)
                    val childLayoutManager = it.layoutManager as LinearLayoutManager?
                    val firstVisibleChildPosition = childLayoutManager?.findFirstVisibleItemPosition() ?: 0
                    val childView = childLayoutManager?.findViewByPosition(firstVisibleChildPosition)
                    childView?.let { view ->
                        // 模拟点击第一个子 item
                        val giftInfo = (it.adapter as GiftChildAdapter).giftBean
                        giftInfo?.apply {

                            selectView?.gone()
                            selectView = view.findViewById(R.id.vBack)
                            selectBean = this
                            selectView!!.visible()
                        }
                    }
                }
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)

                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    val layoutManager = recyclerView.layoutManager as LinearLayoutManager?
                    val firstVisibleItemPosition = layoutManager?.findFirstVisibleItemPosition() ?: 0

                    // 获取当前可见的第一个子 RecyclerView
                    val currentView = layoutManager?.findViewByPosition(firstVisibleItemPosition)
                    val childRecyclerView = currentView?.findViewById<RecyclerView>(R.id.rcvList)
                    childRecyclerView?.let {
                        // 滚动到第一个 item
                        it.scrollToPosition(0)
                        val childLayoutManager = it.layoutManager as LinearLayoutManager?
                        val firstVisibleChildPosition = childLayoutManager?.findFirstVisibleItemPosition() ?: 0
                        val childView = childLayoutManager?.findViewByPosition(firstVisibleChildPosition)
                        childView?.let { view ->
                            // 模拟点击第一个子 item
                            val giftInfo = (it.adapter as GiftChildAdapter).giftBean
                            giftInfo?.apply {
                                selectView?.gone()
                                selectView = view.findViewById(R.id.vBack)
                                selectBean = this
                                selectView!!.visible()
                            }
                        }
                    }
                }
            }
        })

//        binding.llSend.setOnFastClickListener { //   callback.onGiftEntered("")
//            showToast("跳转金币商城")
//        } //  viewModel?.observeNetworkForever(this, observerForever)

     LiveEventBus.get<Any>(NET_WORK_MINE).observe(this) {
            if (it is GetAccountInfoReply) {
                binding.tvSpecies.text = it.account.coins.toString()
            }
        }
     LiveEventBus.get<Any>(NET_WORK_GIFT).observe(this) {
            if (it is GetGiftListReply) {
                initGiftList(it)
            }
        }
        if(GetGiftListReplyManager.getAllGifts().isEmpty()){
            viewModel?.getGiftListApi(GetGiftListRequest.newBuilder().build())
        }else{
            GetGiftListReplyManager.giftListReply?.let { initGiftList(it) }
        }

    }
  fun  initGiftList(it: GetGiftListReply){
      var giftList = mutableListOf<GiftInfo>()
      dataList.clear()
      it.giftListList.forEach {
          if (giftList.size == 8) {
              dataList.add(ArrayList(giftList)) // 添加 giftList 的副本

              giftList = mutableListOf()
              giftList.add(it)
          } else {
              giftList.add(it)
          }
      }


      if (giftList.isNotEmpty()) {
          dataList.add(ArrayList(giftList)) // 添加 giftList 的副本
      }
      dataList.forEach {
          val adapter = GiftChildAdapter {
              selectView?.gone()
              selectView = it.first
              selectBean = it.second
              selectView!!.visible()
          }
          adapterList.add(adapter)
      }
      giftAdapter.notifyDataSetChanged()

      binding.vCircle.setPageCount(giftAdapter.itemCount) // 添加指示器（可选）
    }

    var selectView: View? = null
    var selectBean: GiftInfo? = null
    var adapterList = mutableListOf<BaseQuickAdapter<NewGiftInfo, *>>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, R.style.TUIBeautyDialogTheme)
    }


    val newGiftSelectList: MutableList<MutableList<NewGiftInfo>> = mutableListOf()

    data class NewGiftInfo(var isSelect: Boolean, var bean: GiftInfo)

    private val giftAdapter = object : BaseQuickAdapter<List<GiftInfo>, QuickViewHolder>() {

        override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: List<GiftInfo>?) {
            val rowData = dataList[position]
            val rcvList = holder.getView<RecyclerView>(R.id.rcvList)

            if (rcvList.adapter == null) {
                rcvList.adapter = adapterList[position]
                val newListGiftInfo = mutableListOf<NewGiftInfo>()
                rowData.forEach {
                    newListGiftInfo.add(NewGiftInfo(false, it))
                }
                newGiftSelectList.add(newListGiftInfo)
                adapterList[position].submitList(newListGiftInfo)

            }

        }

        override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
            return QuickViewHolder(R.layout.item_banner_item, parent)
        }
    }


    override fun onDestroy() {
        super.onDestroy()

    }

}